import http from '../../utils/request'
// 获取应用实例
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
       isShow1:false,
        page:1,
        pageSize:10,
        nianjiId:'', //所属年级
        xueduanId:'', //所属学段
        xuekeId:'',//所属学科
        levelId:'', //资源等级
        timeId:'', //适应时间
        areaId:'' ,//适应地区
        xueduanName:'',//所属学段
        leixing:'',
        isshow:'',
        projectItem: [],
        isHideLoadMore:true,
        moreRequest:true,//控制用户手贱多次下拉触发请求
        parms:"",//查询条件参数用于下拉滚动
        speciallist:[],
        //专题等级
        level:[],
        //适应时间
        time:[],
        //适应地区
        area:[],
        leixingids:'',
        selectIsshow:false,
        activeindex:-1,
        activeindex1:-1,
        activeindex2:-1,
        activeindex3:-1,
        activeindex4:-1,
        showTop:false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      console.info(options)
        let classify = options.classifyQuery?JSON.parse(options.classifyQuery):''
        this.resouceLeixing = classify.xueduan?classify.xueduan:'试卷'
        if(classify.xueduanleixing=='level'){
            this.data.xueduanId=classify.xueduanId?classify.xueduanId:undefined //所属学段
        }else if(classify.xueduanleixing=='themetype'){
            this.data.levelId=classify.xueduanId?classify.xueduanId:undefined //资源类型
        }else if(classify.xueduanleixing=='iconitemcaseId'){
            this.data.leixing=classify.xueduanId?classify.xueduanId:undefined
            this.data.xueduanId=classify.xueduan?classify.xueduan:undefined //所属学段
            this.data.xuekeId=classify.xueke?classify.xueke:undefined//所属学科
        }else if(classify.timeName=='适应时间'){
            this.data.timeId=classify.time?classify.time:undefined //适应时间
            this.data.xueduanName=classify.xueduan?classify.xueduan:undefined //所属学段
            this.data.xuekeId=classify.xueke?classify.xueke:undefined //所属学科
        }else{
            this.data.areaId=classify.area?classify.area:undefined //适应时间
            this.data.xueduanName=classify.xueduan?classify.xueduan:undefined //所属学段
            this.data.xuekeId=classify.xueke?classify.xueke:undefined//所属学科
        }
        this.isshow = options.isshow?options.isshow:''
        this.getArticles(1)
        // let mhNameinfo = JSON.parse(wx.getStorageSync('mhName'))
        // let ss = wx.getStorageSync('mhName')
        let mhNameinfo = wx.getStorageSync('mhName')
        let name = mhNameinfo?mhNameinfo.name:'高中'
        let id = mhNameinfo?mhNameinfo.id:11739

        this.getNanji(name) //所属年级
        this.getNavxk(id) //所属学科
        this.resouceLevel() //资源等级
        this.getTime() //适应时间
        this.getArea() //适应地区
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.clearCache();
        this.getArticles(1);//第一次加载数据
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        let {page,loadMore}=this.data
        let that = this
        if (!loadMore) {
            that.setData({
                loadMore: true, //加载中  
                loadAll: false //是否加载完所有数据
            });
            //加载更多，这里做下延时加载
            setTimeout(function() {
                that.getArticles(page);
            }, 1000)
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
      // 获取加载的页面对象
      const pages = getCurrentPages();
      // 获取当前页面的对象
      const currentPage = pages[pages.length - 1];
      console.info(currentPage)
      let url= currentPage.route
      let params=''
     let  allurl = ''
      // console.info(currentPage.options.classifyQuery)
      if(currentPage.options.classifyQuery){
        params = currentPage.options.classifyQuery
        allurl = url+'?classifyQuery='+params
      }else{
        params = currentPage.options.isShow
        allurl = url+'?isShow='+params
      }
      return {
        path:allurl
      }
    },
     // 清缓存
   clearCache:function(){
        this.setData({
            page:1,
            speciallist: [] //文章列表数组清空
        }); 
    },
    async getArticles () {
        //设置默认值
        // let mhNameinfo =  wx.getStorageSync('mhName')
        var that = this;
        var {page,pageSize,nianjiId,levelId,timeId,areaId,xueduanId,xuekeId,leixing,isshow,xueduanName} = this.data;
        var xueke=''
        if(xueduanName){
            xueke =`and n1='${xueduanName}' and n2='${xuekeId}'`
        }else{
            xueke =`and n2='${xuekeId}'`
        }
        var options={
           url:'/getItemCaseByName',
           method:'POST',
           data:{
                page:page,
                pagesize:pageSize,
                levelId:nianjiId?nianjiId:undefined,//所属年级
                subjectId:areaId?areaId:undefined,//适用地区的id
                labelitemcaseId:timeId?timeId:undefined,//适用时间的id
                themetypeId:levelId?levelId:undefined,//资源等级
                sqlwhere:xuekeId?xueke:undefined,//所属学科
                iconitemcaseId:leixing?leixing:undefined,//类型
				isShow:isshow?isshow:undefined, //是否新高考
                type:'资源'
            },
            header:{"content-type":"application/json;charset=UTF-8"}
        }
        let res = await http(options)
        if (res.data.code == 0) {//成功
            if (res.data.obj && res.data.obj.resultItemCases.length > 0) {
                let {page,speciallist,pageSize} = that.data
                page++
                // 这一步实现了上拉加载更多
                res.data.obj.resultItemCases.map(item=>{
                    let extea = item.itemName.substring(item.itemName.lastIndexOf('.')+1).toLowerCase().replace(/\s+/g,"")
                    return Object.assign(item,{suffix:extea})
                })
                let tmpArr = speciallist.concat(res.data.obj.resultItemCases)
                that.setData({
                    speciallist: tmpArr,
                    page:page,
                    loadMore: false
                })
                if (res.data.obj.resultItemCases.length < pageSize) {
                    that.setData({
                      loadMore: false, //隐藏加载中。。
                      loadAll: true //所有数据都加载完了
                    });
                  }
            }else{
                that.setData({
                    loadAll: true, //把“没有数据”设为true，显示  
                    loadMore: false //把"上拉加载"的变量设为false，隐藏  
                  });
            }
        } else {//失败
            console.log(res.data.info);
        }  
     },
    //筛选条件显示
    shaixuanClick(){
        this.setData({selectIsshow:true})
        // this.specialLevel()//专题等级
        // this.getSpecialType() //专题类型
        // this.getTime() //适应时间
        // this.getArea() //适应地区
    },
    // 所属年级
    async getNanji(dataCon){
        let that = this
        let options={
            url:'/getLevel',
            method:'POST'
        }
        let res = await http(options)
        if(res.data.code==0){
            let newNianji = []
            if(dataCon == '高中'||dataCon == '高考'){
                newNianji = res.data.obj.filter(item=> item.levelname!='不限' && item.levelname!='初一' && item.levelname!='初二' && item.levelname!='初三' && item.levelname!='中考')
                that.setData({nianji:newNianji})
            }else{
                newNianji = res.data.obj.filter(item=> item.levelname!='不限' && item.levelname!='高一' && item.levelname!='高二' && item.levelname!='高三' && item.levelname!='高考')
                that.setData({nianji:newNianji})
            }
        }
        that.setData({mhName:res.data})
    },
    //所属学科
    async getNavxk(dataCon){
        let that = this
        let options={
            url:'/getNavs5',
            method:'POST',
            data:{id:dataCon},
            header:{"content-type":"application/json;charset=UTF-8"}
        }
        let res = await http(options)
        // console.info(res)
        // let newNianji = []
        // res.data.map(item=>{
        //     if(item.name!='不限'){
        //         newNianji.push(item)
        //     }
        // })
        that.setData({xueke:res.data})
    },
    //资源等级
    async resouceLevel(){
        let that = this
        let options={
            url:'/getThemetype',
            method:'POST'
        }
        let res = await http(options)
        that.setData({level:res.data.obj})
    },
    //适应时间
    async getTime(){
        let that = this
        let options={
            url:'/getLabelitemcase',
            method:'POST'
        }
        let res = await http(options)
        res.data.obj.map(item=>item.nameNumber=parseInt(item.name))
        res.data.obj.sort((a, b) => a.nameNumber - b.nameNumber)
        that.setData({time:res.data.obj.reverse()})
    },
    //适应地区
    async getArea(){
        let that = this
        let options={
            url:'/getSubject',
            method:'POST'
        }
        let res = await http(options)
        that.setData({area:res.data.obj})
    },
    // 所属年级
    levelClick(e){
        let name = e.currentTarget.dataset.name
        let index = e.currentTarget.dataset.activeindex
        if(name=='不限'){
            this.setData({nianjiId:''})
        }else{
            this.setData({nianjiId:name})
        }
        this.setData({activeindex:index})
    },
    // 所属学科
    stateClick(e){
        let name = e.currentTarget.dataset.name
        let index = e.currentTarget.dataset.activeindex1
        if(name=='不限'){
            this.setData({xuekeId:''})
        }else{
            this.setData({xuekeId:name})
        }
        this.setData({activeindex1:index})
    },
    // 资源等级
    leixingClick(e){
        let name = e.currentTarget.dataset.name
        let index = e.currentTarget.dataset.activeindex2
        if(name=='不限'){
            this.setData({levelId:''})
        }else{
            this.setData({levelId:name})
        }
        this.setData({activeindex2:index})
    },
    // 适应时间
    timeClick(e){
        let name = e.currentTarget.dataset.name
        let index = e.currentTarget.dataset.activeindex3
        if(name=='不限'){
            this.setData({timeId:''})
        }else{
            this.setData({timeId:name})
        }
        this.setData({activeindex3:index})
    },
    // 适应地区
    areaClick(e){
        let name = e.currentTarget.dataset.name
        let index = e.currentTarget.dataset.activeindex4
        if(name=='不限'){
            this.setData({areaId:''})
        }else{
            this.setData({areaId:name})
        }
        this.setData({activeindex4:index})
    },
    // 重置
    reset(){
        this.setData({activeindex:-1,activeindex1:-1,activeindex2:-1,activeindex3:-1,activeindex4:-1, nianjiId:'',xueduanId:'',xuekeId:'',levelId:'',timeId:'',areaId:''})
    },
    // 确定
    sure(){
        this.setData({selectIsshow:false,page:1,speciallist:[]})
        this.getArticles(1)
    },
     //资源详情跳转
     async linkDetail(e){
      let that = this
      let id = e.currentTarget.dataset.id
        let name = e.currentTarget.dataset.name
      let options={
          url:'/getVideoAuthority2',
          method:'POST',
          data:{id:id,userId:wx.getStorageSync('userInfo')?JSON.parse(wx.getStorageSync('userInfo')).id:'0',authorization:wx.getStorageSync('userInfo')?JSON.parse(wx.getStorageSync('userInfo')).authorization:''},
          header:{"content-type":"application/json;charset=UTF-8"}
      }
      let res = await http(options)
        if(res.data.code==0){
          wx.navigateTo({
            url: '/pages/resoucedetail/resoucedetail?id='+id+'&title='+name,
          })
        }else if(res.data.code==1){
          this.setData({isShow1:true})
        }else{
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
            duration: 2000
        })
        }
    },
    stringToJson(data){
        return JSON.parse(data);
      },
      /**
      *字符串转json
      */
      jsonToString(data){
        return JSON.stringify(data);
      },
      //搜所跳转
      searchtap(){
        wx.navigateTo({
        url:'/pages/search/search',
        })
    },
    goTop: function () {
        wx.pageScrollTo({
          scrollTop: 0,
          duration: 300
        })
      }
})